<template>
  <ele-page>
    <!-- 搜索表单 -->
    <base-search @search="reload"/>
    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        highlight-current-row
        cache-key="systemBaseTable"
      >
        <template #toolbar>
          <el-button
            type="primary"
            class="ele-btn-icon"
            :icon="Plus"
            @click="handleInitSchoolDegree()">
            初始化年级
          </el-button>
          <el-button
            type="primary"
            class="ele-btn-icon"
            :icon="Plus"
            @click="openAdd()"
          >
            添加
          </el-button>
          <el-button
            type="danger"
            class="ele-btn-icon"
            :icon="Delete"
            @click="removeBatch()"
          >
            删除
          </el-button>
          <el-button
            plain
            type="primary"
            class="ele-btn-icon"
            :icon="DatabaseOutlined"
            @click="handleSetStudentLead"
          >
            绑定带兵
          </el-button>
          <el-button class="ele-btn-icon" :icon="Upload" @click="openImport">
            导入
          </el-button>
          <el-button class="ele-btn-icon" :icon="Download" @click="exportData">
            导出
          </el-button>
          <el-button class="ele-btn-icon" type="warning" :icon="Lock" @click="encryptData">
            加密数据
          </el-button>
        </template>
        <template #action="{ row }">
          <el-link type="primary" @click="openEdit(row)">
            修改
          </el-link>
          <el-divider direction="vertical"/>
          <el-link type="danger" @click="removeBatch(row)">
            删除
          </el-link>
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 添加弹窗 -->
    <base-add v-model="showAdd" @done="reload"/>
    <!-- 编辑弹窗 -->
    <base-edit v-model="showEdit" :currentId="currentId" @done="reload"/>

    <!--上传弹窗-->
    <base-import v-model="showImport"></base-import>

    <!--设定带兵-->
    <student-set-lead v-model="showSetStudentLead" :data="selectionStudentIds" @done="refresh"></student-set-lead>

  </ele-page>
</template>

<script setup>
import {ref} from 'vue';
import {Plus, Delete, Upload, Download, Lock} from '@element-plus/icons-vue';
import {
  DatabaseOutlined
} from '@/components/icons';
import {ElMessageBox} from 'element-plus/es';
import {EleMessage} from 'ele-admin-plus/es';
import BaseSearch from './components/search.vue';
import BaseAdd from './components/add.vue';
import BaseEdit from './components/edit.vue';
import BaseImport from './components/import.vue';
import StudentSetLead from "./components/student-set-lead.vue";
import {
  pageList,
  removeStudents,
  exportBases,
  initSchoolDegree,
  encryptIdNumber,
}
from
'@/api/manage/student/admin/index.js';

/** 表格实例 */
const tableRef = ref(null);

/** 表格列配置 */
const columns = ref([
  {
    type: 'selection',
    columnKey: 'selection',
    width: 50,
    align: 'center',
    fixed: 'left'
  },
  {
    type: 'index',
    columnKey: 'index',
    minWidth: 50,
    align: 'center',
    fixed: 'left'
  },
  {
    prop: 'code',
    label: '学号',
    align: 'center',
    minWidth: 110
  },
  {
    prop: 'name',
    label: '姓名',
    align: 'center',
    minWidth: 110
  },
  {
    prop: 'sex',
    label: '性别',
    align: 'center',
    minWidth: 110
  },
  {
    prop: 'organization',
    label: '总支',
    align: 'center',
    minWidth: 110
  },
  {
    prop: 'campus',
    label: '校区',
    align: 'center',
    minWidth: 110
  },
  {
    prop: 'grade',
    label: '年级',
    align: 'center',
    minWidth: 110
  },
  {
    prop: 'major',
    label: '专业',
    align: 'center',
    minWidth: 110
  },
  {
    prop: 'studyState',
    label: '学籍状态',
    align: 'center',
    minWidth: 110
  },
  {
    prop: 'graduationYear',
    label: '毕业年份',
    align: 'center',
    minWidth: 110
  },
  {
    prop: 'counsellorName',
    label: '辅导员',
    align: 'center',
    minWidth: 110
  },
  {
    columnKey: 'action',
    label: '操作',
    width: 180,
    align: 'center',
    slot: 'action'
  }
]);

/** 表格选中数据 */
const selections = ref([]);

/** 是否显示添加弹窗 */
const showAdd = ref(false);

/** 当前编辑数据 */
const current = ref(null);

/**
 * 当前编辑的id
 * @type {Ref<UnwrapRef<null>>}
 */
const currentId = ref('');

/** 是否显示编辑弹窗 */
const showEdit = ref(false);


/** 是否显示上传弹窗 */
const showImport = ref(false);


/** 表格数据源 */
const datasource = ({page, limit, where}) => {
  return pageList({...where, pageNum: page, pageSize: limit});
};

/** 搜索 */
const reload = (where) => {
  tableRef.value?.reload?.({page: 1, where});
};

/**
 * 刷新表格
 */
const refresh = () => {
  tableRef.value.reload();
}

/** 打开添加弹窗 */
const openAdd = () => {
  // console.log("openAdd");
  showAdd.value = true;
};

/** 打开编辑弹窗 */
const openEdit = (row) => {
  // console.log("openEdit");
  current.value = row ?? null;
  currentId.value = current.value.id;
  showEdit.value = true;
};

/** 批量删除 */
const removeBatch = (row) => {
  const rows = row == null ? selections.value : [row];
  if (!rows.length) {
    EleMessage.error('请至少选择一条数据');
    return;
  }
  ElMessageBox.confirm(
    `是否确认删除姓名为"${rows.map((d) => d.name).join()}"的数据项?`,
    '系统提示',
    {type: 'warning', draggable: true}
  )
    .then(() => {
      const loading = EleMessage.loading('请求中..');
      removeStudents(rows.map((d) => d.id))
        .then(() => {
          loading.close();
          EleMessage.success('删除成功');
          reload();
        })
        .catch((e) => {
          loading.close();
          EleMessage.error(e.message);
        });
    })
    .catch(() => {
    });
};

/** 导出数据 */
const exportData = () => {
  const loading = EleMessage.loading('请求中..');
  tableRef.value?.fetch?.(({where}) => {
    exportBases(where)
      .then(() => {
        loading.close();
      })
      .catch((e) => {
        loading.close();
        EleMessage.error(e.message);
      });
  });
};


//初始化年级、系别、专业、毕业年份
const handleInitSchoolDegree = () => {
  const loading = EleMessage.loading('处理中..');
  initSchoolDegree().then(response => {
    EleMessage.success('年级、系别、专业初始化成功');
    loading.close();
  });
}

//打开导入窗口
const openImport = () => {
  showImport.value = true;
}


const showSetStudentLead = ref(false);
/** 表格选中学生的id */
const selectionStudentIds = ref([]);
//设定学生带兵辅导员
const handleSetStudentLead = () => {
  const rows = selections.value;
  if (!rows.length) {
    EleMessage.error('请至少选择一条数据');
    return;
  }
  selectionStudentIds.value = rows.map(item => item.id);
  showSetStudentLead.value = true;
}


//加密学生身份证数据
const encryptData = () => {
  const loading = EleMessage.loading('处理中..');
  encryptIdNumber().then(res => {
    EleMessage.success('身份证号加密成功');
    loading.close();
  });
}
</script>
